package com.fuyin.controller;

import cn.hutool.core.io.IoUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.fuyin.commons.exception.ApiException;
import com.fuyin.commons.response.BaseResponse;
import com.fuyin.commons.utils.JwtTokenUtil;
import com.fuyin.dao.GpDao;
import com.fuyin.entity.User;
import com.fuyin.entity.Zcfz;
import com.fuyin.service.RedisService;
import com.fuyin.service.user.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;
import java.util.Objects;

/**
 * @author yuanxilan (yuanxilan@keep.com)
 * @Description
 * @date 2021年11月20日 11:33 下午
 * @since
 */
@Api("内部接口")
@Controller
@RequestMapping(value = "/api")
@Slf4j
public class ApiController {

    @Autowired
    public UserService userService;

    @Autowired
    public GpDao gpDao;

    @Autowired
    public JwtTokenUtil jwtTokenUtil;

    @Autowired
    private RedisService redisService;

    @Value("${jwt.tokenHead}")
    private String tokenHead;

    @ApiOperation("内部接口，请勿访问")
    @GetMapping(value = "/saveAccount")
    public String saveAccount(@RequestParam("token") String token) {
        return userService.saveAccount(token);
    }

    @ApiOperation("内部接口，请勿访问")
    @GetMapping(value = "/log")
    public String log(@RequestParam("log") String token, HttpServletResponse response) {
        if (!"123456".equals(token)) {
            throw new ApiException(403, "没有权限访问");
        }
        try {
            File file = new File("/apps/root/log.file");
            InputStream inputStream = new FileInputStream(file);
            InputStream fis = new BufferedInputStream(inputStream);
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            response.reset();

            //获取文件的名字再浏览器下载页面
            String name = file.getName();
            response.addHeader("Content-Disposition", "attachment;filename=" + new String(name.getBytes(), "utf-8"));
            response.addHeader("Content-Length", "" + file.length());
            OutputStream out = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            out.write(buffer);
            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @ApiOperation("内部接口，请勿访问")
    @GetMapping("/change_email")
    public String changeEamil(@RequestParam("token") String token) {
        return userService.changeEmail(token);
    }

    @ApiOperation("检查 token 是否失效")
    @GetMapping("/checkoutstate")
    @ResponseBody
    public BaseResponse checkOutState(@RequestHeader("Authorization") String token) {
        token = token.substring(this.tokenHead.length());
        boolean isState = redisService.exists(token);
        if (isState) {
            User user = userService.getUserByUserName(jwtTokenUtil.getUserNameFromToken(token));
            if (Objects.isNull(user) || Objects.isNull(user.getType()) || user.getType() < 0 || user.getType() > 2) {
                return BaseResponse.success(-1);
            }
            return BaseResponse.success(user.getType());
        }
        return BaseResponse.success(-1);
    }

    //    @GetMapping("/write-excel")
    public void writeExcel(HttpServletResponse response) {
//        List<String> titles = Arrays.asList("股票代码","股票名字","报告时间","报告类型","报告时间类型","应收账款","应收账款","资本公积","非流动资产中的在建工程","合同负债","递延所得税资产","应收款项融资","非流动资产中的固定资产","商誉","持有代售资产","持有代售负债","无形资产","存货","租赁负债","长期待摊费用","货币资金","应付票据及应付款帐","应收票据及应收款帐","其它流动资产","其它流动负债","其它非流动资产","预计负债","预付款项","实收资本（或股本）","应付职工薪酬","盈余公积","应交税费","资产总计","流动资产总计","流动负债总计","股东权益合计","负债合计","非流动资产合计","非流动负债合计","其它应付款合计","其它应收款合计","归属于母公司股东权益总计","未分配利润","使用权资产","交易性金融资产","递延收益","负债和股东权益总计","审计意见 (境内)");
        List<Zcfz> zcfzs = gpDao.getZcfzList("莎普爱思").subList(0, 1);
        ExcelWriter writer = ExcelUtil.getWriter("./writeBeanTest.xlsx");
        writer.addHeaderAlias("security_code", "股票代码");
        writer.addHeaderAlias("security_name_abbr", "股票名字");
        writer.addHeaderAlias("report_date", "报告时间");
        writer.addHeaderAlias("report_type", "报告类型");
        writer.addHeaderAlias("report_date_name", "报告时间类型");
        writer.addHeaderAlias("accounts_payable", "应收账款");
        writer.addHeaderAlias("accounts_rece", "应收账款");
        writer.addHeaderAlias("capital_reserve", "资本公积");
        writer.addHeaderAlias("cip", "非流动资产中的在建工程");
        writer.addHeaderAlias("contract_liab", "合同负债");
        writer.addHeaderAlias("defer_tax_asset", "递延所得税资产");
        writer.addHeaderAlias("finance_rece", "应收款项融资");
        writer.addHeaderAlias("fixed_asset", "非流动资产中的固定资产");
        writer.addHeaderAlias("goodwill", "商誉");
        writer.addHeaderAlias("holdsale_asset", "持有代售资产");
        writer.addHeaderAlias("holdsale_liab", "持有代售负债");
        writer.addHeaderAlias("intangible_asset", "无形资产");
        writer.addHeaderAlias("inventory", "存货");
        writer.addHeaderAlias("lease_liab", "租赁负债");
        writer.addHeaderAlias("long_prepaid_expense", "长期待摊费用");
        writer.addHeaderAlias("monetaryfunds", "货币资金");
        writer.addHeaderAlias("note_accounts_payable", "应付票据及应付款帐");
        writer.addHeaderAlias("note_accounts_rece", "应收票据及应收款帐");
        writer.addHeaderAlias("other_current_asset", "其它流动资产");
        writer.addHeaderAlias("other_current_liab", "其它流动负债");
        writer.addHeaderAlias("other_noncurrent_asset", "其它非流动资产");
        writer.addHeaderAlias("predict_liab", "预计负债");
        writer.addHeaderAlias("prepayment", "预付款项");
        writer.addHeaderAlias("share_capital", "实收资本（或股本）");
        writer.addHeaderAlias("staff_salary_payable", "应付职工薪酬");
        writer.addHeaderAlias("surplus_reserve", "盈余公积");
        writer.addHeaderAlias("tax_payable", "应交税费");
        writer.addHeaderAlias("total_assets", "资产总计");
        writer.addHeaderAlias("total_current_assets", "流动资产总计");
        writer.addHeaderAlias("total_current_liab", "流动负债总计");
        writer.addHeaderAlias("total_equity", "股东权益合计");
        writer.addHeaderAlias("total_liabilities", "负债合计");
        writer.addHeaderAlias("total_noncurrent_assets", "非流动资产合计");
        writer.addHeaderAlias("total_noncurrent_liab", "非流动负债合计");
        writer.addHeaderAlias("total_other_payable", "其它应付款合计");
        writer.addHeaderAlias("total_other_rece", "其它应收款合计");
        writer.addHeaderAlias("total_parent_equity", "归属于母公司股东权益总计");
        writer.addHeaderAlias("unassign_rpofit", "未分配利润");
        writer.addHeaderAlias("useright_asset", "使用权资产");
        writer.addHeaderAlias("trade_finasset_notfvtpl", "交易性金融资产");
        writer.addHeaderAlias("defer_income", "递延收益");
        writer.addHeaderAlias("total_liab_equity", "负债和股东权益总计");
        writer.addHeaderAlias("opinion_type", "审计意见 (境内)");
        writer.setOnlyAlias(true);
        writer.write(zcfzs, true);
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        response.setHeader("Content-Disposition", "attachment;filename=test.xlsx");

        try {
            writer.flush(response.getOutputStream(), true);
        } catch (IOException e) {
            e.printStackTrace();
        }
        writer.close();
        try {
            IoUtil.close(response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
